package com.ontheroad.mysql.Qiniuyun.service;

import com.google.gson.Gson;
import com.ontheroad.qiniu.service.FileService;
import com.ontheroad.qiniu.service.QiniuyunService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.callback.Callback;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

@Service
public class FileServiceImpl implements FileService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private QiniuyunService qiniuyunService;

    @Override
    public String upload(final InputStream inputStream) {
        return upload(new UploadDone() {
            @Override
            public Response upload(UploadManager uploadManager, String token) throws QiniuException {
                //默认不指定key的情况下，以文件内容的hash值作为文件名
                return uploadManager.put(inputStream, null, token, null, null);
            }
        });
    }

    @Override
    public String upload(final byte[] bytes) {
        return upload(new UploadDone() {
            @Override
            public Response upload(UploadManager uploadManager, String token) throws QiniuException {
                //默认不指定key的情况下，以文件内容的hash值作为文件名
                return uploadManager.put(bytes, null, token);
            }
        });
    }


    private String upload(UploadDone uploadDone) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        String upToken = qiniuyunService.getUploadToken();
        try {
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            Response response = uploadDone.upload(uploadManager, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            String url = qiniuyunService.getDomain() + "/" + putRet.key;
            return url;
        } catch (QiniuException ex) {
            logger.error("文件上传出错：", ex);
        }
        return null;
    }
}

interface UploadDone {
    Response upload(UploadManager uploadManager, String token) throws QiniuException;
}